//
//  StatusViewModel.swift
//  swift_learning
//
//  Created by aron on 2017/2/2.
//  Copyright © 2017年 arons. All rights reserved.
//

import UIKit

class StatusViewModel: NSObject {
    
    /// 微博数据
    var status : Status?
    
    /// 创建时间
    var createdAtText : String?
    
    /// 来源
    var sourceText : String?
    
    /// 头像URL
    var avatarURL : URL?
    
    /// 认证图标
    var verifiedImage : UIImage?
    
    /// vip等级
    var vipImage : UIImage?
    
    /// 配图
    var picUrls : [URL] = [URL]()
    
    init(status : Status) {
        self.status = status
        
        // 处理来源
        if let source = status.source, source != "" {
            
            let sRange = (source as NSString).range(of: ">")
            let eRange = (source as NSString).range(of: "</")
            
            let location = sRange.location + sRange.length
            let length = eRange.location - location
            
            sourceText = (source as NSString).substring(with: NSRange(location: location, length: length))
        }
        
        // 处理时间
        if let createTime = status.created_at {
            createdAtText = Date.createDateString(createAtStr: createTime)
        }
        
        // 处理头像URL
        avatarURL = URL(string: status.user?.avatar_large ?? "")
        
        // 处理认证图像
        let verifiedType = status.user?.verified_type ?? -1
        switch verifiedType {
        case 0:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedImage = nil
        }
        
        // 处理Vip等级图像
        let mbrank = status.user?.mbrank ?? 0
        if mbrank > 0 && mbrank <= 6 {
            vipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
        // 处理配图
        var handledPicUrls : [[String : String]] = [[String : String]]()
        if status.pic_urls.count > 0 {
            handledPicUrls = status.pic_urls
        }else {
            handledPicUrls = status.retweeted_status?.pic_urls ?? [[String : String]]()
        }
        for pic in handledPicUrls {
            if let url = URL(string: pic["thumbnail_pic"] ?? "") {
                picUrls.append(url)
            }
        }
    }
    
}
